package com.ssyt.yt1.day19;

/**
 * 模拟ArrayList
 * 
 * @author Administrator
 *
 */
public class MyArrayListDemo {

	public static void main(String[] args) {
		// List<Integer> list = new ArrayList<Integer>();

		MyArrayList<Integer> myArrayList = new MyArrayList<Integer>(0);
		myArrayList.add(123);
		myArrayList.add(1234);
		myArrayList.add(12345);
		Integer value = 123;
		myArrayList.remove(value);
		myArrayList.add(0, 123);
		for (int i = 0; i < myArrayList.size(); i++) {
			System.out.println(myArrayList.get(i));
		}
	}
}

class MyArrayList<T> {

	private static final int DEFAULT_CAPACITY = 10;
	private Object[] elementData;
	private int size;

	public MyArrayList() {
		elementData = new Object[DEFAULT_CAPACITY];
	}

	public MyArrayList(int initialCapacity) {
		if (initialCapacity > 0) {
			elementData = new Object[initialCapacity];
		} else if (initialCapacity == 0) {
			elementData = new Object[] {};
		} else {
			throw new IllegalArgumentException("Illegal Capacity: "
					+ initialCapacity);
		}
	}

	public void add(T element) {
		ensureCapacity();

		elementData[size++] = element;
	}

	public void add(int index, T element) {
		rangeCheck(index);

		ensureCapacity();

		System.arraycopy(elementData, index, elementData, index + 1, size
				- index);
		elementData[index] = element;
		size++;
	}

	private void ensureCapacity() {
		if (size == elementData.length) {
			Object[] object = new Object[size * 2 + 1];
			System.arraycopy(elementData, 0, object, 0, size);
			elementData = object;
		}
	}

	public void set(int index, T element) {
		rangeCheck(index);

		elementData[index] = element;
	}

	public int size() {
		return size;
	}

	@SuppressWarnings("unchecked")
	public T get(int index) {
		rangeCheck(index);

		return (T) elementData[index];
	}

	private void rangeCheck(int index) {
		if (index < 0 || index >= size) {
			throw new IllegalArgumentException("Index: " + index + ", Size: "
					+ size);
		}
	}

	public void remove(int index) {
		rangeCheck(index);

		int numMoved = size - index - 1;
		if (numMoved > 0) {
			System.arraycopy(elementData, index + 1, elementData, index,
					numMoved);
		}
		elementData[--size] = null; // clear to let GC do its work
	}

	public void remove(T element) {
		for (int index = 0; index < size; index++) {
			if (element == null) {
				if (elementData[index] == null) {
					remove(index);
				}
			} else {
				if (element.equals(elementData[index])) {
					remove(index);
				}
			}
		}
	}
}
